<?php
App::uses ( 'AuthComponent', 'Controller/Component' );
class PostsController extends AppController {
	public $helpers = array (
			'Html',
			'Form',
			'Session' 
	);
	public $components = array (
			'RequestHandler' 
	);
	
	/*
	 * ThanhLD1 - index function this function load data to index.ctp file
	 */
	public function getphpinfo(){
		$this->layout = false;
	}
	
	public function index() {
		
		if ($this->Session->read ( 'Auth.User' )) {
			$loginUser = $this->Session->read ( 'Auth.User' );
		}
		
		// Load model Post
		$this->loadModel ( 'Post' );
		
		$posts = $this->Post->find ( 'all', array (
				'contain' => array (
						'Comment' => array (
								'fullname' 
						),
						'User' 
				),
				'conditions' => 'ORDER BY Post.created DESC LIMIT ' . 10 
		) );
		
		/*
		 * echo '<pre>'; print_r($posts); die;
		 */
		
		// load database with limit 10 rows
		/*
		 * $posts = $this->Post->find ( 'all', array ( 'conditions' => 'ORDER BY Post.created DESC LIMIT ' . 10 ) );
		 */
		
		// if no have data in database of post table or have error occur
		if (! $posts) {
			throw new NotFoundException ( __ ( 'No Data In database!' ) );
		}
		
		// prepair data
		foreach ( $posts as $key => $post ) {
			
			// get review Text to show at homepage
			$textBody = $post ['Post'] ['body'];
			$bodyS = $this->reviewText ( 1000, $textBody );
			$posts [$key] ['Post'] ['body'] = $bodyS;
			
			// get admin username
			$posts [$key] ['Post'] ['username'] = $post ['User'] ['username'];
			
			// get number of comment
			$posts [$key] ['Post'] ['numComment'] = count ( $post ['Comment'] );
			
			// created datetime format
			$formatDate = "F j, o";
			$created = $post ['Post'] ['created'];
			$posts [$key] ['Post'] ['created'] = date ( $formatDate, strtotime ( "$created" ) );
			
			// check thumbnail
			$thumbnail = trim ( $post ['Post'] ['thumbnail'] );
			if (empty ( $thumbnail )) {
				$posts [$key] ['Post'] ['thumbnail'] = "/images/no-photo.jpg";
			}
		}
		
		// prepare data for render view of home (index.ctp)
		$this->set ( 'posts', $posts );
	}
	
	/**
	 * repair a mont-year list for sidebar
	 *
	 * @return unknown
	 */
	public function getSidebarList() {
		if ($this->request->is ( 'requested' )) {
			
			$resultList = $this->Post->find ( 'all', array (
					'fields' => array (
							"concat(EXTRACT(YEAR FROM Post.created), '-', EXTRACT(MONTH FROM Post.created)) as month_year" 
					),
					'order' => array (
							'month_year DESC' 
					),
					'group' => array (
							'month_year' 
					) 
			) );
			
			return $resultList;
		}
	}
	
	/**
	 * get list of posts base on month-year of post created day
	 *
	 * @param unknown $monthYear        	
	 */
	public function listByMonth($monthYear) {
		$resultList = $this->Post->find ( 'all', array (
				'contain' => array (
						'Comment' 
				),
				'conditions' => array (
						"concat(EXTRACT(YEAR FROM created), '-', EXTRACT(MONTH FROM created))" => $monthYear 
				),
				'order' => array (
						'Post.created DESC' 
				) 
		) );
		
		$this->loadModel ( 'User' );
		foreach ( $resultList as $key => $post ) {
			// get admin username
			$resultList [$key] ['Post'] ['username'] = $post ['User'] ['username'];
			// check thumbnail
			$thumbnail = trim ( $post ['Post'] ['thumbnail'] );
			if (empty ( $thumbnail )) {
				$resultList [$key] ['Post'] ['thumbnail'] = "/images/no-photo.jpg";
			}
		}
		
		// print_r($resultList); exit;
		$this->set ( 'posts', $resultList );
	}
	
	/**
	 *
	 * @param string $id        	
	 */
	public function detail($id = null) {
		$detail = $this->Post->find ( 'first', array (
				'contain' => array (
						'Comment' => array (
								'fullname',
								'id',
								'content',
								'created' 
						),
						'User' 
				),
				'conditions' => array (
						'Post.id' => $id 
				) 
		) );
		
		// demo translate behavior
		 $this->loadModel ( 'Comment' );
		Configure::write('Config.language', 'frech');
		
		echo Configure::read('Config.language');
		
		echo '<pre>';
		print_r ( $this->Comment->find ( 'all', array (
				'conditions' => array (
						'post_id' => 9 
				) 
		) ) );
		die (); 
		// end demo
		
		// check if detail is exist
		if ($detail == null) {
			$this->Session->setFlash ( 'This post is not exist', 'default', array (
					'class' => 'alert alert-danger' 
			) );
			return $this->redirect ( array (
					'controller' => 'posts',
					'action' => 'index' 
			) );
		}
		
		// pull data
		$postDetail = array (
				'Post' => $detail ['Post'] 
		);
		$poster = array (
				'Poster' => $detail ['User'] 
		);
		$comments = $detail ['Comment'];
		
		// check if this post is belong to current logined user
		$isAuthor = false;
		if ($this->Session->check ( 'Auth.User' )) {
			$logined = $this->Session->read ( 'Auth.User' );
			if ($logined ['id'] == $postDetail ['Post'] ['user_id']) {
				$isAuthor = true;
			} else if ($this->Acl->check ( $this->Auth->user ( 'role' ), 'manageAllPost' )) {
				$isAuthor = true;
			}
		}
		
		$thumbnail = trim ( $postDetail ['Post'] ['thumbnail'] );
		if (empty ( $thumbnail )) {
			$postDetail ['Post'] ['thumbnail'] = "/images/no-photo.jpg";
		}
		
		$this->set ( 'detail', $postDetail );
		$this->set ( 'comments', $comments );
		$this->set ( 'poster', $poster );
		
		// $this->set ( 'sidebarList', $sidebarList );
		// check is this user author of this post.
		$this->set ( 'isAuthor', $isAuthor );
	}
	
	/*
	 * ThanhLD1 - process function This function load more data from current position at home page set data to process.ctp and return html and append at current data from home page index.ctp
	 */
	public function process() {
		// Set layout is empty
		$this->layout = "";
		
		// Load model Post
		$this->loadModel ( 'Post' );
		
		// get position of list post to countinues loading - ThanhLD1
		if (isset ( $_POST ['start'] ) && ( int ) ($_POST ['start'])) {
			$start = $_POST ['start'];
		} else {
			$start = 10;
		}
		
		// get more data start at current data on homepage index.ctp
		$posts = $this->Post->find ( 'all', array (
				'contain' => array (
						'Comment' => array (
								'fullname' 
						),
						'User' 
				),
				'conditions' => 'ORDER BY created DESC LIMIT ' . $start . ', 10' 
		) );
		
		// if no have data in database of post table or have error occur
		if (! $posts) {
			throw new NotFoundException ( __ ( 'No Data In database!' ) );
		}
		
		// prepair data
		foreach ( $posts as $key => $post ) {
			
			// get review Text to show at homepage
			$textBody = $post ['Post'] ['body'];
			$bodyS = $this->reviewText ( 1000, $textBody );
			$posts [$key] ['Post'] ['body'] = $bodyS;
			
			// get admin username
			$posts [$key] ['Post'] ['username'] = $post ['User'] ['username'];
			
			// get number of comment
			$posts [$key] ['Post'] ['numComment'] = count ( $post ['Comment'] );
			
			// created datetime format
			$formatDate = "F j, o";
			$created = $post ['Post'] ['created'];
			$posts [$key] ['Post'] ['created'] = date ( $formatDate, strtotime ( "$created" ) );
		}
		
		// return value to append current data at homepage index.ctp
		$this->set ( 'posts', $posts );
	}
	
	/*
	 * ThanhLD1 - review text This function return a string with maxlength had given to review at homepage
	 */
	// function get text to show review on home page - ThanhLD1
	private function reviewText($maxLength, $html) {
		if (! $html)
			return "";
			// remove all tag html - ThanhLD1
		$result = trim ( strip_tags ( $html ) );
		if (empty ( $result )) {
			$result = "<p style=\"color: red;\">SORRY! NO REVIEW TEXT!</p>";
		}
		// cut string with length is maxLength - ThanhLD1
		if (strlen ( $result ) > $maxLength) {
			$pos = strpos ( $result, ' ', $maxLength );
			$result = substr ( $result, 0, $pos );
			$result .= "....";
		}
		return $result;
	}
	public function beforeFilter() {
		parent::beforeFilter ();
		$this->Auth->allow ();
		$this->viewClass = "Smarty";
	}
	public function download() {
		$this->viewClass = 'Media';
		// Download app/outside_webroot_dir/example.zip
		$params = array (
				'id' => 'testDoc.docx',
				'name' => 'nameNew',
				'download' => true,
				'extension' => 'docx',
				'path' => APP . 'outside_webroot_dir' . DS 
		);
		$this->set ( $params );
	}
	public function download1() {
		$this->viewClass = 'Media';
		$params = array (
				'id' => 'abc.docx',
				'name' => 'abc',
				'extension' => 'docx',
				'mimeType' => array (
						'docx' => 'application/vnd.openxmlformats-officedocument.wordprocessingml.document' 
				),
				'path' => 'files' . DS 
		);
		$this->set ( $params );
	}
	public function download2() {
		$this->viewClass = 'Media';
		$params = array (
				'id' => '202.pdf',
				'name' => '202',
				'extension' => 'pdf',
				'mimeType' => array (
						'pdf' => 'application/pdf' 
				),
				'path' => 'files' . DS 
		);
		$this->set ( $params );
	}
	public function viewDataView() {
		$posts = $this->Post->find ( 'all', array (
				'contain' => array (
						'Comment' => array (
								'fullname' 
						),
						'User' 
				),
				'conditions' => 'ORDER BY Post.created DESC LIMIT ' . 10 
		) );
		
		$this->set ( 'posts', $posts );
		
		$this->set ( '_serialize', array (
				'posts' 
		) );
	}
	public function testSmart() {
		$this->Post->unbindModel ( array (
				'hasMany' => array (
						'Comment' 
				) 
		) );
		$this->Post->unbindModel ( array (
				'belongsTo' => array (
						'User' 
				) 
		) );
		
		$detail = $this->Post->find ( 'first', array (
				'contain' => array (
						'Comment' => array (
								'fullname',
								'id',
								'content',
								'created' 
						),
						'User' 
				) 
		) );
		
		// $abc = dirname(APP) . DS . 'vendors' . DS. 'smarty' . DS . 'plugins'. DS;
		/*
		 * echo TMP . 'smarty' . DS .	 'compile' . DS; die;
		 */
		
		/* $this->layout="";
		$this->render(false); 
		
		$smarty = new Smarty;
		
		//remove
		$smarty->setTemplateDir(APP . 'View' . DS . 'Posts');
		
		$smarty->assign('name', 'abc smit asdfasdfasd fasdh');
		$smarty->assign('address', '107 a quang trung');
		
		$smarty->assign('Contacts', array('fax' => '555-222-9876',
				'email' => 'zaphod@slartibartfast.example.com',
				'phone' => array('home' => '555-444-3333',
						'cell' => '555-111-1234')
		));
		
		$arr = array(1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30);
		
		$smarty->assign('detail', $detail);	
		
		$smarty->assign('arr', $arr);
		
		$smarty->assign('date123', '2014-2-15');
		$smarty->display('test_Smart.tpl');   */

		
 		   $this->set ( 'detail', $detail );
		$this->set ( 'name', 'dao viet hung' );
		$this->set ( 'addrees', '12321312' );
		$this->set ( 'date123', "2014-2-15" );
		$arr = array (
				1,
				2,
				3,
				4,
				5,
				6,
				7,
				8,
				9,
				10,
				11,
				12,
				13,
				14,
				15,
				16,
				17,
				18,
				19,
				20,
				21,
				22,
				23,
				24,
				25,
				26,
				27,
				28,
				29,
				30 
		);
		
		$this->set ( 'arr', $arr );
		
		$obj = new Object();
		
		$this->set($obj);		
	}
}